package com.example.qxfw.qxxx.controller;

import com.dmgis.service.DmServiceConnector;
import com.example.qxfw.common.SysResult;
import com.example.qxfw.common.entity.xt.ContourSetting;
import com.example.qxfw.common.util.GridUtil;
import com.example.qxfw.common.util.TxtFileManager;
import com.example.qxfw.mongodb.qx.entity.QxGridFile;
import com.example.qxfw.mongodb.qx.service.QxGridFileService;
import com.example.qxfw.qxxx.entity.GridDataPicAndXY;
import com.example.qxfw.qxxx.entity.LongitudeLatitudeValue;
import com.example.qxfw.qxxx.service.ContourSettingService;
import com.example.qxfw.qxxx.service.RefinedForecastingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import static java.lang.System.err;


@Slf4j
@Api(tags = "气象信息-精细化预报")
@RestController
@CrossOrigin
@RequestMapping("/RefinedForecastingController")
@Log4j2
public class RefinedForecastingController {

    private static final String pluginClassFullName = "contourservice";

    private static final String methodName = "GetInterpolationWork";

    @Autowired
    private QxGridFileService qxGridFileService;

    @Autowired
    private RefinedForecastingService refinedForecastingService;
    @Autowired
    private ContourSettingService contourSettingService;
    @Autowired
    private TxtFileManager txtFileManager;


    @Value("${filePath.imagePath}")
    private String imageUrl;

    @Value("${txt.file.txtIp}")
    private String txtIp;

    @Value("${txt.file.txtPort}")
    private String txtPort;

    @Value("${filePath.txtFilePath}")
    private String path;

    @Value("${dmgis.ip}")
    private String serverName;

    @Value("${dmgis.port}")
    private String port;

    @Autowired
    private GridUtil gridUtil;


    @RequestMapping(value = "/girdView")
    @ApiOperation("气象信息-精细化预报-gird格点")
    public SysResult gridView(String dateChar, String timeChar, String nTimes, String type, String type1) throws IOException {
        if (type.equals("EDA10.U")) {
            QxGridFile qxGridFileU = qxGridFileService.queryListByDateCharTimeCharNtimesType(dateChar, timeChar, nTimes, type);
            QxGridFile qxGridFileV = qxGridFileService.queryListByDateCharTimeCharNtimesType(dateChar, timeChar, nTimes, type1);
            if (qxGridFileU == null || qxGridFileV == null) return SysResult.success(null);
            Map<String, Object> mapU = gridUtil.processGridData(qxGridFileU);
            Map<String, Object> mapV = gridUtil.processGridData(qxGridFileV);
            //}
            Double[] lonsUArray = (Double[]) mapU.get("lons");
            Double[] latsUArray = (Double[]) mapU.get("lats");
            Double[] valsUArray = (Double[]) mapU.get("vals");

            Double[] lonsVArray = (Double[]) mapV.get("lons");
            Double[] latsVArray = (Double[]) mapV.get("lats");
            Double[] valsVArray = (Double[]) mapV.get("vals");

            // 将数组转换为 List
            List<Double> lonsU = Arrays.asList(lonsUArray);
            List<Double> latsU = Arrays.asList(latsUArray);
            List<Double> valsU = Arrays.asList(valsUArray);

            List<Double> lonsV = Arrays.asList(lonsVArray);
            List<Double> latsV = Arrays.asList(latsVArray);
            List<Double> valsV = Arrays.asList(valsVArray);

            // 计算结果
            List<Double> windAngles = new ArrayList<>();
            List<Double> windValues = new ArrayList<>();

            for (int i = 0; i < valsU.size(); i++) {
                double u = valsU.get(i);
                double v = valsV.get(i);

                double[] windAngle = new double[1];
                double[] windValue = new double[1];

                uvConvertToWind(u, v, windAngle, windValue);

                windAngles.add(windAngle[0]);
                windValues.add(windValue[0]);
            }

            // 整合所有数据
            Map<String, Object> result = new HashMap<>();
            result.put("lons", lonsU);
            result.put("lats", latsU);
            result.put("vals", windValues);
            String paramtype = "雨量";
            if (type.equals("ER03"))//雨
            {
                paramtype = "雨量";
            } else if (type.equals("ERH")) {
                paramtype = "湿度";
            } else if (type.equals("ECT")) {
                paramtype = "气压";
            } else if (type.equals("EDA10.U")) {
                paramtype = "风速";
            } else if (type.equals("TMP")) {
                paramtype = "温度";
            }
            List<ContourSetting> list1 = contourSettingService.getList(paramtype);
            return SysResult.success(result, list1);
        } else {
            QxGridFile qxGridFileU = qxGridFileService.queryListByDateCharTimeCharNtimesType(dateChar, timeChar, nTimes, type);
            if (qxGridFileU == null) return SysResult.success(null);
            Map<String, Object> result = gridUtil.processGridData(qxGridFileU);
            String paramtype = "雨量";
            if (type.equals("ER03"))//雨
            {
                paramtype = "雨量";
            } else if (type.equals("ERH")) {
                paramtype = "湿度";
            } else if (type.equals("ECT")) {
                paramtype = "气压";
            } else if (type.equals("EDA10.U")) {
                paramtype = "风速";
            } else if (type.equals("TMP")) {
                paramtype = "温度";
            }
            List<ContourSetting> list1 = contourSettingService.getList(paramtype);
            return SysResult.success(result, list1);
        }

}


        // String paramtype = "雨量";
        // if(type.equals("ER03"))//雨
        // {
        //     paramtype = "雨量";
        // }
        // else if(type.equals("ERH"))
        // {
        //     paramtype = "湿度";
        // }
        // else if(type.equals("ECT"))
        // {
        //     paramtype = "气压";
        // }
        // else if(type.equals("EDA10.U"))
        // {
        //     paramtype = "风速";
        // }
        // else if(type.equals("TMP"))
        // {
        //     paramtype = "温度";
        // }
        // List<ContourSetting> list1 = contourSettingService.getList(paramtype);
        //
        //
        // return SysResult.success(result,list1);


    @RequestMapping(value = "/mapView")
    @ApiOperation("气象信息-精细化预报-gird成图")
    public ResponseEntity<byte[]> mapView(String dateChar, String timeChar, String nTimes, String type) throws IOException {
        QxGridFile qxGridFile = qxGridFileService.queryListByDateCharTimeCharNtimesType(dateChar, timeChar, nTimes, type);

        String name = dateChar +"_"+ timeChar +"_"+ nTimes +"_"+ type;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG); // 设置为图片的MIME类型
        headers.setContentDisposition(ContentDisposition.builder("attachment").filename(name + ".png").build());
        if(qxGridFile == null) return new ResponseEntity<>(null, headers, HttpStatus.OK);
        String paramtype = "雨量";
        if(type.equals("ER03"))//雨
        {
            paramtype = "雨量";
        }
        else if(type.equals("ERH"))
        {
            paramtype = "湿度";
        }
        else if(type.equals("ECT"))
        {
            paramtype = "云量";
        }
        else if(type.equals("EDA10.U"))
        {
            paramtype = "风速";
        }
        else if(type.equals("TMP"))
        {
            paramtype = "温度";
        }
        List<ContourSetting> contourSetting = qxGridFileService.getContourSetting(paramtype);

//        byte[] data = gridUtil.processGridDataPic(qxGridFile,contourSetting);
        GridDataPicAndXY gridDataPicAndXY = gridUtil.processGridDataPicAndXY(qxGridFile, contourSetting);
        headers.add("xMin", String.valueOf(gridDataPicAndXY.getxMin()));
        headers.add("xMax", String.valueOf(gridDataPicAndXY.getxMax()));
        headers.add("yMin", String.valueOf(gridDataPicAndXY.getyMin()));
        headers.add("yMax", String.valueOf(gridDataPicAndXY.getyMax()));
        return new ResponseEntity<>(gridDataPicAndXY.getFiledata(), headers, HttpStatus.OK);
    }

    @RequestMapping(value = "/ContourMap", method = RequestMethod.GET)
    @ApiOperation("气象信息-精细化预报-等值图url")
    public String ContourMap(String dateChar, String timeChar, String nTimes, String type, String elementType) {
       return "";
//        QxGridFile qxGridFile = qxGridFileService.queryListByDateCharTimeCharNtimesType(dateChar, timeChar, nTimes, type);
//
//        List<LongitudeLatitudeValue> longitudeLatitudeValueList;
//        try {
//            longitudeLatitudeValueList = gridUtil.processGridData(qxGridFile);
//            List<ContourSetting> contourSettingList = refinedForecastingService.queryByElementType(elementType);
//            //txt数据
//            String txt = txtFileManager.getGridTxt(longitudeLatitudeValueList, contourSettingList);
//
//            try {
//                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
//                // 生成文件名，格式为时间+RefinedForecastingController
//                String txtName = dateFormat.format(new Date()) + "RefinedForecastingController";
//                //写入文件
//                String txtPath = txtFileManager.writeDataToTxtFile(txt, txtName);
//                //文件夹目录
//                String homePath = TxtFileManager.extractFolderPath(txtPath);
//                // 一小时删除任务
//                TxtFileManager.cleanupTempFiles(homePath, 3600000);
//
//                err.println("文件存储路径：" + txtPath);
//
//                String url = "http://" + txtIp + ":" + txtPort +"/"+ txtName + ".txt";
//                err.println(url);
//
//                DmServiceConnector conn = new DmServiceConnector(serverName, port);
//                //返回等值图点集json的插件服务
//                String callPlugin = conn.getCallPlugin(pluginClassFullName, methodName, url);
//
//                //out.println(callPlugin);
//                System.out.println(callPlugin);
//                //返回等值图图片url
// //                String callPlugin1 = conn.getCallPlugin("contourservice", "GetContourPic", callPlugin + "|yl|500|500|109.53914234,21.6297788700001,110.893801633,23.127373617|1");
// //                err.println(callPlugin1);
// //                return "192.168.0.15:81/" + callPlugin1;
//                return callPlugin;
//
//            } catch (IOException e) {
//                e.printStackTrace();
//                return "Error writing file.";
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//            return "Error processing grid data.";
//        }
//
}

    /*@ApiOperation("气象信息-精细化预报-等值图url")
    @GetMapping("/getIsograph")
    public Object getIsograpg(String dateChar, String timeChar, String nTimes, String type){

        QxGridFile qxGridFile = qxGridFileService.queryListByDateCharTimeCharNtimesType(dateChar, timeChar, nTimes, type);


        return null;
    }*/

    @RequestMapping(value = "/queryContourSetting", method = RequestMethod.GET)
    @ApiOperation("气象信息-精细化预报-获取分级参数以及基准色")
    public SysResult queryContourSetting(String elementType) {
        List<ContourSetting> contourSettingList = refinedForecastingService.queryByElementType(elementType);
        return SysResult.success(contourSettingList);
    }
    //计算风速方法
    public static void uvConvertToWind(double u, double v, double[] windAngle, double[] windValue) {
        final double p = 180 / Math.PI;
        final double k = Math.PI / 2;
        windValue[0] = Math.sqrt(u * u + v * v);
        windValue[0] = Math.round(windValue[0] * 10) / 10.0;
        if (v != 0) {
            if (u == 0) {
                windAngle[0] = v > 0 ? 0 : 2 * k;
            } else if (u > 0) {
                windAngle[0] = v > 0 ? (k - Math.atan(v / u)) : (k + Math.atan(-v / u));
            } else {
                windAngle[0] = v > 0 ? (3 * k + Math.atan(-v / u)) : (3 * k - Math.atan(v / u));
            }
        } else {
            if (u > 0) {
                windAngle[0] = k;
            } else if (u < 0) {
                windAngle[0] = 3 * k;
            } else {
                windAngle[0] = 0;
            }
        }

        windAngle[0] = windAngle[0] * p;
        if (windAngle[0] > 180) {
            windAngle[0] -= 180;
        } else {
            windAngle[0] += 180;
        }
    }
}
